<?php
namespace app\admin\controller;

use think\Exception;
use think\Db;
use app\common\model\coin\CoinList;
use app\common\controller\Log;
use app\common\model\coin\CoinUser;
use app\common\model\user\Users;
use app\common\controller\Base64;
use think\Config;
use app\common\model\cash\CashRecharge;
use app\common\model\cash\CashList;

class Coin extends Base
{
	/**
	 * 添加币种
	 * @throws Exception
	 * @return unknown
	 */
	public function addCoin()
	{
		$data = $this->request->post();
		Db::startTrans();
		try {
			if(!$data['name'])throw new Exception('请输入币种名称');
			if(!$data['address'])throw new Exception('请输入充币地址');
			if(CoinList::where(['name' => $data['name'],'state' => 1])->value('id'))
				throw new Exception('币种已存在');
			$data['create_time'] = time();
			$data['update_time'] = time();
			//添加币种
			CoinList::create($data);
			//添加操作日志
			Log::addLog(1, '添加币种【'.$data['name'].'】');
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}
	/**
	 * 上传图片
	 * @return unknown
	 */
	public function upImage()
	{
		$data = $this->request->post('');
		$base64 = new Base64();
		$res = $base64 ->up_base64($data['img'], Config::get('path.coin'));
		return jsonSuccess($res);
	}
	/**
	 * 币种列表
	 * @return unknown
	 */
	public function coinList()
	{
		$all = $this -> request -> post('all');
		if($all){
			$list = CoinList::where(['state' => 1])->field('id,name')->select()->toArray();
			foreach ($list as &$val) {
				$val['label'] = $val['name'];
				$val['value'] = $val['id'];
			}
			array_unshift($list, ['value' => 0,'label' => '全部']);
		}else{
			$list = CoinList::where(['state' => 1])->order('id desc')->paginate();
		}
		
		return jsonSuccess($list);
	}
	
	/**
	 * 删除币种
	 * @throws Exception
	 * @return unknown
	 */
	public function deleteCoin()
	{
		$data = $this->request->post('');
		$id = $data['id'];
		Db::startTrans();
		try {
			if(is_array($id)){
				CoinList::where(['id' => ['in',$id]])->update(['update_time' => time() , 'state' => 0]);
				//添加日志
				$coin_name = CoinList::where(['id' => ['in',$id]])->column('name');
				foreach ($coin_name as $val) {
					Log::addLog(3, "删除币种【{$val}】");
				}
			}else{
				$coin = CoinList::get($id);
				if(!$coin->state)throw new Exception('状态错误');
				$coin->save(['update_time' => time(),'state' => 0]);
				//添加日志
				Log::addLog(3, "删除币种【{$coin->name}】");
			}
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('删除成功');
	}
	
	/**
	 * 用户币种数据
	 * @return unknown
	 */
	public function coinUser()
	{
		$data = $this->request->post('');
		//初始化查询条件
		$where = [];
		if(!empty($data['user_name'])){
			$user_id = Users::where(['user_name' => $data['user_name'] ])->value('id');
			$where['user_id'] = $user_id;
		}
		if(!empty($data['coin']))$where['coin_id'] = $data['coin'];
		$list = CoinUser::where($where)->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$rows['user_info'] = Users::get($rows['user_id']);
			$rows['coin_info'] = CoinList::get($rows['coin_id']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 人工充值
	 * @throws Exception
	 * @return unknown
	 */
	public function rechargeCoin()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//验证数据合法性
			if(!$data['user_name'])throw new Exception('请输入用户账号');
			if(!$data['coin_id'])throw new Exception('请选择币种');
			if(!$data['num'] || $data['num'] < 0)throw new Exception('请输入充值数量');
			//验证数据正确性
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			if(!$user_id)throw new Exception('用户不存在');
			$coin = CoinList::get($data['coin_id']);
			if(!$coin)throw new Exception('币种不存在');
			$user_coin = CoinUser::where(['user_id' => $user_id , 'coin_id' => $data['coin_id']])->find();
			if(!$user_coin)throw new Exception('该用户没有该币种账户');
			//充币
			CoinUser::where(['user_id' => $user_id , 'coin_id' => $data['coin_id']])->setInc('avalible_price',$data['num']);
			//添加充值记录
			$info = [
					'user_id' => $user_id,
					'coin_id' => $data['coin_id'],
					'num' => $data['num'],
					'recharge_way' => 1,
					'address' => $user_coin['address'],
					'state' => 1,
					'create_time' => time(),
					'update_time' => time()
			];
			CashRecharge::create($info);
			//添加日志
			Log::addLog(2, "给用户".$data['user_name']."充值".$data['num']."$coin->name");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('充值成功');
	}
	
	/**
	 * 人工充值记录
	 * @return unknown
	 */
	public function rechargeList()
	{
		$list = CashRecharge::where(['recharge_way' => 1])->order('id desc')->paginate();
		return jsonSuccess($list);
	}
	
	/**
	 * 人工扣款
	 * @throws Exception
	 * @return unknown
	 */
	public function cash()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			//验证数据合法性
			if(!$data['user_name'])throw new Exception('请输入用户账号');
			if(!$data['coin_id'])throw new Exception('请选择币种');
			if(!$data['num'] || $data['num'] < 0)throw new Exception('请输入充值数量');
			//验证数据正确性
			$user_id = Users::where(['user_name' => $data['user_name']])->value('id');
			if(!$user_id)throw new Exception('用户不存在');
			$coin = CoinList::get($data['coin_id']);
			if(!$coin)throw new Exception('币种不存在');
			$user_coin = CoinUser::where(['user_id' => $user_id , 'coin_id' => $data['coin_id']])->find();
			if(!$user_coin)throw new Exception('该用户没有该币种账户');
			if($user_coin['avalible_price'] < $data['num'])$data['num'] = $user_coin['avalible_price'];
			//扣款
			CoinUser::where(['user_id' => $user_id , 'coin_id' => $data['coin_id']])->setDec('avalible_price',$data['num']);
			//添加扣款记录
			$info = [
					'user_id' => $user_id,
					'coin_id' => $data['coin_id'],
					'num' => $data['num'],
					'ready_num' => $data['num'],
					'fee' => 0,
					'surplus_num' => CoinUser::where(['user_id' => $user_id , 'coin_id' => $data['coin_id']])->value('avalible_price'),
					'cash_way' => 1,
					'address' => $user_coin['address'],
					'state' => 1,
					'create_time' => time(),
					'update_time' => time()
			];
			CashList::create($info);
			//添加日志
			Log::addLog(2, "给用户".$data['user_name']."扣除".$data['num']."$coin->name");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('扣款成功');
	}
	
	/**
	 * 扣款记录
	 * @return unknown
	 */
	public function cashList()
	{
		$list = CashList::where(['cash_way' => 1])->order('id desc') -> paginate();
		return jsonSuccess($list);
	}
}